/*
 * Copyright (c) 2019.  Cloud-Star. Co. Ltd. All rights reserved.
 */

package cn.com.liuxiaoluxx.cloud.api.interceptor;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.liuxiaoluxx.cloud.facade.pojo.AuthUser;
import lombok.extern.slf4j.Slf4j;


/**
 * @author liuxiaolu
 */
@Slf4j
public class AuthHandlerInterceptor implements HandlerInterceptor {

    /**
     * 认证信息key
     */
    private final static String LOGIN_TOKEN_KEY = "X-Token";

    /**
     * 未认证标识
     */
    private final static int UNAUTHORIZED_CODE = 401;

    private final StringRedisTemplate stringRedisTemplate;

    public AuthHandlerInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("url: {}", request.getServletPath());
        String xToken = request.getHeader(LOGIN_TOKEN_KEY);
        if (StringUtils.isBlank(xToken)) {
            response.setStatus(UNAUTHORIZED_CODE);
            return false;
        }

        String sessionData = stringRedisTemplate.opsForValue().get(xToken);
        if (StringUtils.isBlank(sessionData)) {
            response.setStatus(UNAUTHORIZED_CODE);
            return false;
        }

        AuthUser authUser = JSON.parseObject(sessionData, AuthUser.class);

        request.setAttribute("authUser", authUser);

        return true;
    }
}
